//
//  ZCAdjustmentDetailViewController.m
//  ZhiChe-Wms
//
//  Created by 高睿婕 on 2018/9/6.
//  Copyright © 2018年 Regina. All rights reserved.
//

#import "ZCAdjustmentDetailViewController.h"
#import "ZCAbnormalMissingTableViewCell.h"
#import "ZCTaskTotalNumTableViewCell.h"
#import "ZCAdjustmentModel.h"
#import "ZCAdjustmentLocationViewController.h"
#import "ZCAssignCodeEditVinViewController.h"

static NSString *missCellID = @"ZCAbnormalMissingTableViewCell";
static NSString *numCellID = @"ZCTaskTotalNumTableViewCell";

@interface ZCAdjustmentDetailViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *adjustButton;
@property (nonatomic, strong) ZCAdjustmentInfoModel *detailModel;
@property (nonatomic, copy) NSString *destLocation;
@property (nonatomic, copy) NSString *destLocationId;
@property (nonatomic, strong) MBProgressHUD *hud;
@property (nonatomic, assign) BOOL carLocation;
@property (nonatomic, assign) BOOL bindLocation;

@end

@implementation ZCAdjustmentDetailViewController
#pragma mark - 懒加载
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, space(90 * 7) + 64) style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
            _tableView.scrollIndicatorInsets = _tableView.contentInset;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        }
        _tableView.scrollEnabled = NO;
        [_tableView registerClass:[ZCAbnormalMissingTableViewCell class] forCellReuseIdentifier:missCellID];
        [_tableView registerClass:[ZCTaskTotalNumTableViewCell class] forCellReuseIdentifier:numCellID];
    }
    return _tableView;
}

- (UIButton *)adjustButton {
    if (!_adjustButton) {
        _adjustButton = [[UIButton alloc] init];
        [_adjustButton setTitle:@"确认调整" forState:UIControlStateNormal];
        [_adjustButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_adjustButton setBackgroundColor:ZCColor(0xff8213, 0.6)];
        _adjustButton.enabled = NO;
        _adjustButton.layer.masksToBounds = YES;
        _adjustButton.layer.cornerRadius = space(6);
        [_adjustButton addTarget:self action:@selector(adjustButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _adjustButton;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"库位调整";
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    [backButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.adjustButton];
    __weak typeof(self)weakSelf = self;
    [self.adjustButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view.mas_left).offset(space(80));
        make.right.equalTo(weakSelf.view.mas_right).offset(-space(80));
        make.top.equalTo(weakSelf.tableView.mas_bottom).offset(space(80));
        make.height.mas_equalTo(space(90));
    }];
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hud];
    [self loadData];
    self.carLocation = NO;
    self.bindLocation = NO;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.adjustButton setBackgroundColor:ZCColor(0xff8213, 0.6)];
    if (self.destLocation.length > 0) {
        self.adjustButton.enabled = YES;
        [self.adjustButton setBackgroundColor:ZCColor(0xff8213, 1)];

    }
    if (!self.bindLocation && self.carLocation) {
        self.adjustButton.enabled = YES;
        [self.adjustButton setBackgroundColor:ZCColor(0xff8213, 1)];
        [self.adjustButton setTitle:@"实车确认" forState:UIControlStateNormal];
        self.carLocation = YES;
    }else {
        [self.adjustButton setTitle:@"确认调整" forState:UIControlStateNormal];
        if (self.destLocation.length > 0) {
            self.adjustButton.enabled = YES;
            [self.adjustButton setBackgroundColor:ZCColor(0xff8213, 1)];
        }else {
            self.adjustButton.enabled = NO;
            [self.adjustButton setBackgroundColor:ZCColor(0xff8213, 0.6)];
        }
        self.carLocation = NO;
        [self loadData];
    }
    [self.tableView reloadData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.hud hideAnimated:YES];
    self.hud.mode = MBProgressHUDModeIndeterminate;
}

#pragma mark - 网络请求
- (void)loadData {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:self.houseId forKey:@"houseId"];
    if (self.carLocation) {
        self.visitType = @"SCAN";
        self.key = self.detailModel.lotNo1;
    }
    [param setObject:self.visitType forKey:@"visitType"];
    [param setObject:self.key forKey:@"key"];
    
    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:AdjustmentDetail params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue] == 0) {
                [weakSelf.hud hideAnimated:YES];
                weakSelf.detailModel = [ZCAdjustmentInfoModel yy_modelWithDictionary:responseObject[@"data"]];
                [weakSelf.tableView reloadData];
            }else {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
}


#pragma mark - 按钮点击
- (void)backButtonClick:(UIButton *)sender {
//    if (!self.bindLocation && self.carLocation) {
//        self.hud.mode = MBProgressHUDModeText;
//        self.hud.label.text = @"请进行实车确认";
//        [self.hud showAnimated:YES];
//        [self.hud hideAnimated:YES afterDelay:HudTime];
//    }else {
        [self.navigationController popViewControllerAnimated:YES];
//    }
    
}

- (void)adjustButtonClick:(UIButton *)sender {
    if (!self.carLocation) {
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [param setObject:self.detailModel.storeHouseId forKey:@"condition[houseId]"];
        [param setObject:self.detailModel.stockId forKey:@"condition[stockId]"];
        [param setObject:self.destLocationId forKey:@"condition[newLocationId]"];
        
    self.hud.mode = MBProgressHUDModeIndeterminate;
    self.hud.label.text = @"";
        [self.hud showAnimated:YES];
        __weak typeof(self)weakSelf = self;
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [ZCHttpTool postWithURL:AdjustmentCommit params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if ([responseObject[@"code"] integerValue] == 0) {
                    [weakSelf.hud hideAnimated:YES];
                    weakSelf.carLocation = YES;
                    weakSelf.destLocation = @"";
                    weakSelf.bindLocation = NO;
                    [sender setTitle:@"实车确认" forState:UIControlStateNormal];
                    [weakSelf loadData];
//                    [weakSelf.navigationController popViewControllerAnimated:YES];
                }else {
                    weakSelf.hud.mode = MBProgressHUDModeText;
                    weakSelf.hud.label.text = responseObject[@"message"];
                    [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
                }
            } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = error.localizedDescription;
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }];
        });
    }else {
        ZCAssignCodeEditVinViewController *editVC = [[ZCAssignCodeEditVinViewController alloc] init];
        editVC.key = self.detailModel.lotNo1;
        editVC.name = @"location";
        __weak typeof(self)weakSelf = self;
        editVC.bindCodeBlock = ^(BOOL bind) {
            weakSelf.bindLocation = bind;
        };
        [self.navigationController pushViewController:editVC animated:YES];
    }

}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 7;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 5 || indexPath.row == 6) {
        ZCAbnormalMissingTableViewCell *missCell = [tableView dequeueReusableCellWithIdentifier:missCellID forIndexPath:indexPath];
        missCell.selectionStyle = UITableViewCellSelectionStyleNone;
        missCell.titleColor = ZCColor(0x000000, 0.87);
        missCell.contentColor = ZCColor(0xff8213, 1);
        if (indexPath.row == 5) {
            missCell.title = @"目的库位";
            missCell.content = self.destLocation;
            missCell.canSelected = YES;
        }else {
            missCell.title = @"实车位置";
            missCell.content = self.detailModel.storeDetail;
            missCell.canSelected = NO;
        }
       
        return missCell;
    }else {
        ZCTaskTotalNumTableViewCell *numCell = [tableView dequeueReusableCellWithIdentifier:numCellID forIndexPath:indexPath];
        numCell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row == 0) {
            numCell.title = @"车架号";
            numCell.content = self.detailModel.lotNo1;
        }else if (indexPath.row == 1) {
            numCell.title = @"客户";
            numCell.content = self.detailModel.ownerId;
        }else if (indexPath.row == 2) {
            numCell.title = @"车型";
            numCell.content = self.detailModel.materielId;
        }else if (indexPath.row == 3) {
            numCell.title = @"仓库";
            numCell.content = self.detailModel.storeHouseName;
        }else if (indexPath.row == 4) {
            numCell.title = @"当前库位";
            numCell.content = [NSString stringWithFormat:@"%@ %@",self.detailModel.storeAreaName, self.detailModel.locationName];
            numCell.contentColor = ZCColor(0xff8213, 1);
        }
        return numCell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return space(90);
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 5) {
        ZCAdjustmentLocationViewController *locationVC = [[ZCAdjustmentLocationViewController alloc] init];
        __weak typeof(self)weakSelf = self;
        locationVC.locationBlock = ^(NSString *location, NSString *locationId) {
            weakSelf.destLocation = location;
            weakSelf.destLocationId = locationId;
        };
        [self.navigationController pushViewController:locationVC animated:YES];
    }
}


@end
